import 'dart:math';

import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:intl/intl.dart';
import '../service/database_service.dart';

class FeedingStats extends StatefulWidget {
  final String babyId;
  final DateTimeRange dateRange;

  const FeedingStats({Key? key, required this.babyId, required this.dateRange})
    : super(key: key);

  @override
  _FeedingStatsState createState() => _FeedingStatsState();
}

class _FeedingStatsState extends State<FeedingStats> {
  String _selectedPeriod = '7天';
  final List<String> _periods = ['7天', '30天', '90天'];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _buildPeriodSelector(),
        Expanded(
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Column(
                children: [
                  // _buildDailyFeedingChart(),
                  // SizedBox(height: 24),
                  _buildFeedingTimesDistribution(),
                  SizedBox(height: 24),
                  _buildFeedingSummary(),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPeriodSelector() {
    return Padding(
      padding: EdgeInsets.all(16),
      child: SegmentedButton<String>(
        segments:
            _periods
                .map(
                  (period) => ButtonSegment(value: period, label: Text(period)),
                )
                .toList(),
        selected: {_selectedPeriod},
        onSelectionChanged: (Set<String> newSelection) {
          setState(() {
            _selectedPeriod = newSelection.first;
          });
        },
      ),
    );
  }

  Widget _buildDailyFeedingChart() {
    return FutureBuilder<List<DailyFeedingSummary>>(
      future: DatabaseService().getDailyFeedingSummary(widget.babyId),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.data!.isEmpty) {
          return const Center(child: Text('暂无数据'));
        }

        final data = snapshot.data!;
        final maxCount = data.map((e) => e.count).reduce(max).toDouble();
        final maxAmount = data.map((e) => e.totalAmount).reduce(max).toDouble();

        return Card(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('每日喂养趋势', style: Theme.of(context).textTheme.titleLarge),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Icon(
                      Icons.circle,
                      color: Theme.of(context).primaryColor,
                      size: 12,
                    ),
                    const SizedBox(width: 4),
                    const Text('次数'),
                    const SizedBox(width: 16),
                    Icon(
                      Icons.circle,
                      color: Theme.of(context).colorScheme.secondary,
                      size: 12,
                    ),
                    const SizedBox(width: 4),
                    const Text('总量(ml)'),
                  ],
                ),
                const SizedBox(height: 16),
                SizedBox(
                  height: 200,
                  child: LineChart(
                    LineChartData(
                      lineTouchData: LineTouchData(
                        touchTooltipData: LineTouchTooltipData(
                          tooltipBgColor: Colors.black87,
                          getTooltipItems: (spots) {
                            return spots.map((spot) {
                              final date = data[spot.x.toInt()].date;
                              final isCount = spots.indexOf(spot) == 0;
                              return LineTooltipItem(
                                '${DateFormat('MM/dd').format(date)}\n'
                                '${isCount ? "次数: ${spot.y.toInt()}" : "总量: ${spot.y.toInt()}ml"}',
                                TextStyle(
                                  color:
                                      isCount
                                          ? Theme.of(context).primaryColor
                                          : Theme.of(
                                            context,
                                          ).colorScheme.secondary,
                                ),
                              );
                            }).toList();
                          },
                        ),
                      ),
                      lineBarsData: [
                        LineChartBarData(
                          spots: List.generate(data.length, (i) {
                            return FlSpot(
                              i.toDouble(),
                              data[i].count.toDouble(),
                            );
                          }),
                          isCurved: true,
                          color: Theme.of(context).primaryColor,
                          dotData: const FlDotData(show: false),
                        ),
                        LineChartBarData(
                          spots: List.generate(data.length, (i) {
                            return FlSpot(
                              i.toDouble(),
                              data[i].totalAmount.toDouble(),
                            );
                          }),
                          isCurved: true,
                          color: Theme.of(context).colorScheme.secondary,
                          dotData: const FlDotData(show: false),
                        ),
                      ],
                      titlesData: FlTitlesData(
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              if (value.toInt() >= data.length)
                                return const Text('');
                              final date = data[value.toInt()].date;
                              return Padding(
                                padding: const EdgeInsets.only(top: 8.0),
                                child: Text(
                                  DateFormat('MM/dd').format(date),
                                  style: const TextStyle(
                                    fontSize: 10,
                                    color: Colors.grey,
                                  ),
                                ),
                              );
                            },
                            interval: 1,
                          ),
                        ),
                        leftTitles: AxisTitles(
                          axisNameWidget: const Text(
                            '次数',
                            style: TextStyle(fontSize: 10, color: Colors.grey),
                          ),
                          sideTitles: getSideTitles(maxCount),
                        ),
                        rightTitles: AxisTitles(
                          axisNameWidget: const Text(
                            '总量(ml)',
                            style: TextStyle(fontSize: 10, color: Colors.grey),
                          ),
                          sideTitles: getSideTitles(maxAmount),
                        ),
                        topTitles: const AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                      ),
                      gridData: FlGridData(
                        drawVerticalLine: false,
                        horizontalInterval: _calculateInterval(maxCount),
                        getDrawingHorizontalLine:
                            (value) => FlLine(
                              color: Colors.grey.withOpacity(0.1),
                              strokeWidth: 1,
                            ),
                      ),
                      borderData: FlBorderData(
                        show: true,
                        border: Border(
                          bottom: BorderSide(color: Colors.grey.shade300),
                          left: BorderSide(color: Colors.grey.shade300),
                          right: BorderSide(color: Colors.grey.shade300),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildFeedingTimesDistribution() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('喂养时间分布', style: Theme.of(context).textTheme.titleLarge),
            SizedBox(height: 16),
            SizedBox(
              height: 200,
              child: FutureBuilder<Map<int, int>>(
                future: DatabaseService().getFeedingDistribution(
                  babyId: widget.babyId,
                  dateRange: widget.dateRange,
                ),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) {
                    return Center(child: CircularProgressIndicator());
                  }

                  final maxY = snapshot.data!.values.reduce(max).toDouble();
                  final interval = _calculateInterval(maxY);

                  return BarChart(
                    BarChartData(
                      alignment: BarChartAlignment.spaceAround,
                      maxY: maxY,
                      barGroups:
                          snapshot.data!.entries.map((entry) {
                            return BarChartGroupData(
                              x: entry.key,
                              barRods: [
                                BarChartRodData(
                                  toY: entry.value.toDouble(),
                                  color: Theme.of(context).primaryColor,
                                  width: 12,
                                  borderRadius: BorderRadius.vertical(
                                    top: Radius.circular(4),
                                  ),
                                ),
                              ],
                            );
                          }).toList(),
                      titlesData: FlTitlesData(
                        leftTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              if (value == 0) return const SizedBox.shrink();
                              return Text(
                                value.toInt().toString(),
                                style: TextStyle(
                                  color: Colors.grey[600],
                                  fontSize: 10,
                                ),
                              );
                            },
                            interval: interval,
                            reservedSize: 28,
                          ),
                        ),
                        bottomTitles: AxisTitles(
                          sideTitles: SideTitles(
                            showTitles: true,
                            getTitlesWidget: (value, meta) {
                              // Only show every 3 hours
                              if (value.toInt() % 3 != 0) {
                                return const SizedBox.shrink();
                              }
                              return Padding(
                                padding: const EdgeInsets.only(top: 5),
                                child: Text(
                                  '${value.toInt()}时',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 10,
                                  ),
                                ),
                              );
                            },
                            reservedSize: 24,
                          ),
                        ),
                        rightTitles: AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                        topTitles: AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                      ),
                      gridData: FlGridData(
                        show: true,
                        drawVerticalLine: false,
                        horizontalInterval: interval,
                        getDrawingHorizontalLine:
                            (value) => FlLine(
                              color: Colors.grey.withOpacity(0.1),
                              strokeWidth: 1,
                            ),
                      ),
                      borderData: FlBorderData(show: false),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFeedingSummary() {
    return FutureBuilder<Map<String, dynamic>>(
      future: DatabaseService().getFeedingSummary(
        babyId: widget.babyId,
        dateRange: widget.dateRange,
      ),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(child: CircularProgressIndicator());
        }

        final data = snapshot.data!;
        return Column(
          children: [
            _buildSummaryCard(
              title: '统计概要',
              items: [
                SummaryItem(
                  icon: Icons.touch_app,
                  label: '总次数',
                  value: '${data['totalCount']}次',
                ),
                SummaryItem(
                  icon: Icons.opacity,
                  label: '总量',
                  value: '${data['totalAmount']}ml',
                ),
                SummaryItem(
                  icon: Icons.schedule,
                  label: '平均间隔',
                  value: '${data['averageInterval']}小时',
                ),
                SummaryItem(
                  icon: Icons.bar_chart,
                  label: '日均次数',
                  value: '${data['averageDaily']}次',
                ),
              ],
            ),
            SizedBox(height: 16),
            _buildSummaryCard(
              title: '时段分析',
              items: [
                SummaryItem(
                  icon: Icons.wb_sunny,
                  label: '白天(6:00-18:00)',
                  value: '${data['daytimeCount']}次',
                ),
                SummaryItem(
                  icon: Icons.nightlight,
                  label: '夜间(18:00-6:00)',
                  value: '${data['nightCount']}次',
                ),
                SummaryItem(
                  icon: Icons.trending_up,
                  label: '最多时段',
                  value: '${data['peakHour']}:00',
                ),
                SummaryItem(
                  icon: Icons.access_time,
                  label: '平均用时',
                  value: '${data['averageDuration']}分钟',
                ),
              ],
            ),
          ],
        );
      },
    );
  }

  Widget _buildSummaryCard({
    required String title,
    required List<SummaryItem> items,
  }) {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: Theme.of(context).textTheme.titleLarge),
            SizedBox(height: 16),
            GridView.count(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              crossAxisCount: 2,
              childAspectRatio: 2.5,
              children:
                  items.map((item) {
                    return Row(
                      children: [
                        Icon(item.icon, color: Theme.of(context).primaryColor),
                        SizedBox(width: 8),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              item.label,
                              style: Theme.of(context).textTheme.bodySmall,
                            ),
                            Text(
                              item.value,
                              style: Theme.of(context).textTheme.titleMedium,
                            ),
                          ],
                        ),
                      ],
                    );
                  }).toList(),
            ),
          ],
        ),
      ),
    );
  }
}

class SummaryItem {
  final IconData icon;
  final String label;
  final String value;

  const SummaryItem({
    required this.icon,
    required this.label,
    required this.value,
  });
}

SideTitles getSideTitles(double maxValue) {
  final interval = _calculateInterval(maxValue);
  return SideTitles(
    showTitles: true,
    getTitlesWidget: (value, meta) {
      if (value == 0) return const SizedBox.shrink();
      return Padding(
        padding: const EdgeInsets.only(right: 8),
        child: Text(
          value.toInt().toString(),
          style: const TextStyle(fontSize: 10, color: Colors.grey),
          textAlign: TextAlign.right,
        ),
      );
    },
    interval: interval,
    reservedSize: 32, // Increased reserved size
  );
}

double _calculateInterval(double maxValue) {
  if (maxValue <= 0) return 1;

  // Aim for 4-5 labels
  final double rawInterval = maxValue / 4;

  // Round to nice numbers
  if (rawInterval <= 1) return 1;
  if (rawInterval <= 2) return 2;
  if (rawInterval <= 5) return 5;
  if (rawInterval <= 10) return 10;
  if (rawInterval <= 20) return 20;
  if (rawInterval <= 50) return 50;

  return (rawInterval / 100).ceil() * 100;
}
